const puppeteer = require('puppeteer');
const https = require('https');
const { execSync } = require('child_process');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
class PuppeteerHelper {
  /** 
  * 页面等待
  */
  async pageWait(time) {
    await new Promise(resolve => setTimeout(resolve, time));
  }
  constructor(options = {}) {
    this.browser = null;
    this.page = null;
    this.options = Object.assign({
      headless: false,
      userDataDir: 'userdata',
      // defaultViewport: { width: 1600, height: 900 },
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox'
      ],
      ignoreDefaultArgs: ['--enable-automation'],
      slowMo: 50,
      // args: ['--window-size=1200,700']
    }, options);
  }
  /**
   * 获取系统中 Chrome 浏览器的安装路径   
   */
  getChromeInstallationPath() {
    try {
      // 执行注册表查询命令
      const command = 'reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe" /ve';
      const output = execSync(command).toString();

      // 解析注册表输出，提取安装路径
      const match = output.match(/REG_SZ\s+(.+)/);
      if (match && match.length >= 2) {
        return match[1];
      }
    } catch (error) {
      // 处理错误
      console.error('无法获取 Chrome 安装路径:', error);
    }

    return null;
  }


  async init() {
    // let chromePath = this.getChromeInstallationPath();
    // if (chromePath) {
    // this.options.executablePath = chromePath;
    this.options.headless = false;
    this.browser = await puppeteer.launch(this.options);
    // 获取已打开的页面列表
    const pages = await this.browser.pages();
    if (pages.length > 0)
      this.page = pages[0];
    else this.page = await this.browser.newPage();
    // 修改 window.navigator.webdriver 属性
    await this.page.evaluateOnNewDocument(() => {
      // 在页面加载前执行以下脚本，将 window.navigator.webdriver 设置为 false
      Object.defineProperty(navigator, 'webdriver', {
        get: () => false,
      });
    });
    // const page = await browser.newPage();
    // 获取当前屏幕尺寸
    const screenSize = await this.page.evaluate(() => {
      return {
        width: window.screen.width,
        height: window.screen.height,
        deviceScaleFactor: window.devicePixelRatio
      };
    });
    // 设置页面视口大小为全屏
    await this.page.setViewport(screenSize);
    // }
  }


  async waitForAction(act) {
    await this.page.waitForFunction((expectedAct) => {
      return window.action === expectedAct;
    }, { timeout: 2147483647 }, act);
  }

  async close() {
    await this.browser.close();
  }
  downloadImage(imageUrl, outputPath) {
    return new Promise((resolve, reject) => {
      const fileStream = fs.createWriteStream(outputPath);

      const request = https.get(imageUrl, (response) => {
        response.pipe(fileStream);

        fileStream.on('finish', () => {
          fileStream.close();
          resolve();
        });
      });

      request.on('error', (error) => {
        reject(error);
      });
    });
  }
  async getAllImages(dataList) {
    console.log('开始获取图片列表', dataList[0]);
    try {
      const imgList = [];
      for (const linkElement of dataList) {
        const href = linkElement.auctionURL;
        const src = linkElement.pic_path;
        imgList.push({
          src: src,
          href: href,
        });
      }
      var id = 0;
      for (const item of imgList) {
        const fileName = `${++id}.png`;
        console.log('开始下载...', fileName);
        await this.downloadImage(item.src, `images/${fileName}`);
        item.fileName = fileName;
        // 生成随机等待时间（1到3秒之间）
        const randomWaitTime = Math.floor(Math.random() * 2000) + 1000;
        // 等待随机等待时间
        await new Promise(resolve => setTimeout(resolve, randomWaitTime));
      }


      // 将数组保存到 imgList.json 文件中
      fs.writeFileSync('imgList.json', JSON.stringify(imgList));
    }
    catch (error) {
      console.log(error);
    }

  }
}

module.exports = new PuppeteerHelper();
// //测试用例
// const helper = new PuppeteerHelper();
// (async () => {
//   await helper.init();
//   helper.page.goto("https://www.baidu.com")
//   console.log('loaded');
// })();